﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace OfficeClip.OpenSource.SpellO
{
	public partial class SettingsForm : Form
	{
		public Form1 parentForm;
		public SettingsForm()
		{
			InitializeComponent();
		}

		public SettingsForm(Form1 frm1): this()
		{
			parentForm = frm1;
		}

		private void SettingsForm_Load(object sender, EventArgs e)
		{
			int index = parentForm.GetCurrentIndex();
			Settings.Site site = parentForm.spello.Sites[index];
			SettingsBL settings = new SettingsBL();
			settings.Id = site.Id;
			settings.BaseUrl = site.BaseUri;

			settings.MaxCrawlDepth = site.Crawler.MaxCrawlDepth;
			settings.ThreadCount = site.Crawler.ThreadCount;
			settings.WorkItemPriority = site.Crawler.WorkItemPriority;
			settings.AdhereToRobotRules = site.Crawler.AdhereToRobotRules;
			settings.DownloadDelay = site.Crawler.DownloadDelay;
			settings.UserAgent = site.Crawler.UserAgent;
            settings.AllowedUrls = GetMultiLineFromList(site.Crawler.AllowedUrls);
            settings.DisallowedUrls = GetMultiLineFromList(site.Crawler.DisallowedUrls);
			settings.ProcessHtmlFilter = GetMultiLineFromFilterList(site.Crawler.ProcessHtmlFilter);
			settings.ProcessLinkFilter = GetMultiLineFromFilterList(site.Crawler.ProcessLinkFilter);

			settings.ShowSuggestions = site.SpellCheck.ShowSuggestions;
			settings.MinimumWordLength = site.SpellCheck.MinimumWordLength;
			settings.IgnoreAllCapitals = site.SpellCheck.IgnoreAllCapitals;
            settings.Dictionary = site.SpellCheck.Dictionary;
            settings.AllowWords = GetMultiLineFromList(site.SpellCheck.AllowWords);
			propertyGrid1.SelectedObject = settings;
		}

        private string GetMultiLineFromList(List<string> list)
        {
            if (list == null) return string.Empty;
            list.Sort();
            StringBuilder sb = new StringBuilder();
            foreach (string str in list)
            {
                sb.Append(str + System.Environment.NewLine);
            }
            return sb.ToString();
        }

		private string GetMultiLineFromFilterList(List<Settings.Filter> filterList)
		{
            if (filterList == null) return string.Empty;
            filterList.Sort();
            StringBuilder sb = new StringBuilder();
			foreach (Settings.Filter filter in filterList)
			{
				sb.AppendFormat("%s,%s%s", filter.Start, filter.End, System.Environment.NewLine);
			}
			return sb.ToString();
		}

		private List<Settings.Filter> GetFilterListFromMultiLine(string strMultiLine)
		{
			List<Settings.Filter> list = new List<Settings.Filter>();
			string[] astr = strMultiLine.Split(
				System.Environment.NewLine.ToCharArray(),
				StringSplitOptions.RemoveEmptyEntries
				);
			string[] astr1;
			foreach (string str in astr)
			{
				astr1 = str.Split(",".ToCharArray());
				if (astr1.Length != 2)
				{
					throw new Exception("Filters should always be put in pairs. e.g <code>,</code>");
				}
				list.Add(new Settings.Filter(astr1[0], astr[1]));
			}
			return list;
		}

		private List<string> GetListFromMultiLine(string strMultiLine)
        {
            List<string> list = new List<string>();
            string[] astr = strMultiLine.Split(
                System.Environment.NewLine.ToCharArray(),
                StringSplitOptions.RemoveEmptyEntries
                );
            foreach (string str in astr)
            {
                list.Add(str);
            }
            return list;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
           
            SettingsBL settings = (SettingsBL)propertyGrid1.SelectedObject;
            Settings.Site site = new OfficeClip.OpenSource.SpellO.Settings.Site();
            site.Id = settings.Id;
            if (settings.BaseUrl == string.Empty)
            {
                MessageBox.Show("BaseUrl missing",
                       "Error",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error,
                        MessageBoxDefaultButton.Button1
                );
                return;
            }
            else if (!settings.BaseUrl.StartsWith("http://") || !settings.BaseUrl.StartsWith("http://"))
            {
                MessageBox.Show("BaseUrl must start with http:// or https://",
                       "Error",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error,
                        MessageBoxDefaultButton.Button1
                );
                return;
            }
            else
            {
                site.BaseUri = settings.BaseUrl;
            }

            site.Crawler = new OfficeClip.OpenSource.SpellO.Settings.Crawler();
            site.Crawler.AdhereToRobotRules = settings.AdhereToRobotRules;
            site.Crawler.DownloadDelay = settings.DownloadDelay;
            site.Crawler.MaxCrawlDepth = settings.MaxCrawlDepth;
            site.Crawler.ThreadCount = settings.ThreadCount;
            site.Crawler.WorkItemPriority = settings.WorkItemPriority;
			site.Crawler.UserAgent = settings.UserAgent;
			site.Crawler.AllowedUrls = GetListFromMultiLine(settings.AllowedUrls);
			site.Crawler.DisallowedUrls = GetListFromMultiLine(settings.DisallowedUrls);
			try
			{
				site.Crawler.ProcessHtmlFilter = GetFilterListFromMultiLine(settings.ProcessHtmlFilter);
				site.Crawler.ProcessLinkFilter = GetFilterListFromMultiLine(settings.ProcessLinkFilter);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message,
                        "Error",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error,
                        MessageBoxDefaultButton.Button1
                );
				return;
			}

            site.SpellCheck = new OfficeClip.OpenSource.SpellO.Settings.SpellCheck();
            site.SpellCheck.AllowWords = GetListFromMultiLine(settings.AllowWords);
            site.SpellCheck.ShowSuggestions = settings.ShowSuggestions;
            site.SpellCheck.MinimumWordLength = settings.MinimumWordLength;
            site.SpellCheck.IgnoreAllCapitals = settings.IgnoreAllCapitals;
            string str = settings.Dictionary;
            str = Constants.GetSetupDir() + @"\" + str;
            if (
                !File.Exists(str + ".dic") ||
                !File.Exists(str + ".aff")
                )
            {
                MessageBox.Show("Spell Checker dictionary or its associated files are not found",
                        "Error",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error,
                        MessageBoxDefaultButton.Button1
                );
                return;
            }
            else //Patch to enable the saving of Dictionary settings
            {
                site.SpellCheck.Dictionary = settings.Dictionary;
            }

            int index = parentForm.GetCurrentIndex();
            parentForm.spello.Sites[index] = site;
            Constants.Serialize(parentForm.spello);
            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void propertyGrid1_Click(object sender, EventArgs e)
        {

        }

        private void SettingsForm_Resize(object sender, EventArgs e)
        {
            //Lets change the useable are on window resizing
            this.propertyGrid1.Height = this.Height - 71;
            this.propertyGrid1.Width = this.Width - 28;

            this.btnSave.Top = this.Height - 58 ;
            this.btnSave.Left = this.Width - 132; 
            
            this.btnCancel.Top = this.Height - 58;
            this.btnCancel.Left = this.Width - 73;

        }


	}
}
